package com.briup.mt.web.controller;

import com.briup.mt.bean.Dataset;
import com.briup.mt.bean.DatasetFile;
import com.briup.mt.service.IFileDatasetService;
import com.briup.mt.utils.ExcelUtils;
import com.briup.mt.utils.Message;
import com.briup.mt.utils.MessageUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.formula.eval.UnaryMinusEval;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import javax.xml.namespace.QName;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author pete
 * @version 1.0
 * @date 2020/12/16 11:42
 */
@RestController
@Validated
@RequestMapping("/dataset")
public class FileDatasetController {
    @Autowired
    private IFileDatasetService fileDatasetService;

    @ApiOperation(value = "导入到Excel中", notes = "注意！测试的时候请将地址粘贴到浏览器地址栏测试", produces = "fileDataset/octet-stream")
    @GetMapping("download")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "模型名称", required = true, paramType = "query"),})
            public void download(HttpServletResponse response, String name) throws Exception {
        // 2. 将excel导出
        // 2.1 excel头部数据
        String[] headList = new String[] { "姓名", "介绍", "图片" };
        // 2.2 属性
        String[] fieldList = new String[] { "name", "introduce", "photo" };
        // 2.3 数据列，需要转化
        List<Map<String, Object>> dataList = new ArrayList<>();
        List<Dataset> list = fileDatasetService.query(name);
        for (Dataset app : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("name", app.getName());
            map.put("introduce", app.getIntroduce());
            map.put("photo", app.getPhoto());
            dataList.add(map);
        }
        // 2.4 导出文件名
        String excelName = "fileDataset";
        // 3. 调用工具方法导出Excel
        ExcelUtils.createExcel(response, excelName, headList, fieldList, dataList);

    }

    @GetMapping("query")
    public Message query(String name){
        List<Dataset> list = fileDatasetService.query(name);
        return MessageUtil.success(list);
    }

    @PostMapping("saveOrUpdate")
    public Message saveOrUpdate(Dataset data){
        fileDatasetService.saveOrUpdate(data);
        return MessageUtil.success("操作成功");
    }

    @DeleteMapping("deleteByID")
    @ApiImplicitParams({@ApiImplicitParam(name = "id",value="用户编号",required =true, paramType = "query"),})

    public Message deleteByID(@NotNull long id){
        fileDatasetService.deleteById(id);
        return MessageUtil.success("操作成功");
    }
}
